package com.demo2.todo.repository;

import com.demo2.todo.model.entity.Tag;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;

import java.util.List;
import java.util.Optional;

/**
 * @author evi
 */
public interface TagRepository extends JpaRepository<Tag, Long> {

    Optional<Tag> findByIdAndUserId(Long id, Long userId);

    List<Tag> findByUserId(Long id);

    Optional<Tag> findByNameAndUserId(String trim, Long id);

    // 新增关联表操作
    @Query(value = "SELECT tag_id FROM todo_tags WHERE todo_id = :todoId", nativeQuery = true)
    List<Long> findTagIdsByTodoId(@Param("todoId") Long todoId);

    @Modifying
    @Query(value = "DELETE FROM todo_tags WHERE todo_id = :todoId", nativeQuery = true)
    void deleteByTodoId(@Param("todoId") Long todoId);

    @Modifying
    @Query(value = "INSERT INTO todo_tags (todo_id, tag_id) VALUES (:todoId, :tagId)", nativeQuery = true)
    void insertTagRelation(@Param("todoId") Long todoId, @Param("tagId") Long tagId);
    /**
     * 根据待办事项ID删除标签关联
     */
    @Modifying
    @Query(value = "DELETE FROM todo_tags WHERE todo_id = :todoId", nativeQuery = true)
    void deleteTagRelationsByTodoId(@Param("todoId") Long todoId);
}
